package org.example.producer.service;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.util.Constant;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 生产服务
 *
 * @since 2022/7/12
 **/
@Service
@Slf4j
public class ProduceService {

    private static final ExecutorService executorService = Executors.newFixedThreadPool(2);

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 添加数据到redis
    public void addToRedis() {
        // 操作Redis中的string类型的数据,先获取ValueOperation
        ListOperations<String, String> valueOperations = stringRedisTemplate.opsForList();
        while (true) {
            LinkedList<String> list = new LinkedList<>();
            for (int i = 0; i < 500; i++) {
                list.add(RandomUtil.randomString(10));
            }
            // 添加数据到redis
            valueOperations.leftPushAll(Constant.key, list);
        }
    }

    public Runnable getRunnable() {
        return new Runnable() {
            @Override
            public void run() {
                addToRedis();
            }
        };
    }

    public void run() {
        log.debug("调用");
        for (int i = 0; i < 4; i++) {
            executorService.submit(getRunnable());
        }
    }

}
